import { useState, useEffect, useMemo } from 'react';
import { Form, message } from 'antd';
import moment from 'moment';

import { ExpertsUpdateService } from '../services/UpdateService';
import { IActionEnum } from '../common/ExpertsReducer';
import { arieaEchoRender } from '@/utils';

const { success, warning } = message;
export function useExpertsUpdate({
  locationProps,
  expertsInfo,
  dispatch,
  expertQualifies,
}: {
  locationProps: Record<string, any>;
  expertsInfo: Record<string, any>;
  dispatch: any;
  expertQualifies: Record<string, any>[];
}) {
  const { title = '查看专家信息', type = 'view', info = {} } = locationProps?.state || {};

  // 渲染证书弹窗
  const [certificateStatus, setCertificateStatus] = useState({
    state: false,
    operate: 'add',
  });
  // 分页证书信息
  const [current, setCurrent] = useState<number>(1);

  const [baseInfoForm] = Form.useForm();
  const [certificateInfoForm] = Form.useForm();

  const { addExpertsService, findExpertsService, editExpertsService, addExpertsCertificateService, editExpertsCertificateService } = ExpertsUpdateService();

  const { addExpertsRun } = addExpertsService();
  const { findExpertsRun, findExpertsLoading } = findExpertsService();
  const { editExpertsRun } = editExpertsService();
  const { addExpertsCertificateRun } = addExpertsCertificateService();
  const { editExpertsCertificateRun } = editExpertsCertificateService();

  const isView = useMemo(() => type == 'view', [type]);

  const onChangeExpertsCertificateInfoState = (state: boolean, operate = 'add') => {
    certificateInfoForm.resetFields();
    setCertificateStatus({
      state: state,
      operate: operate,
    });
  };

  // 添加专家信息
  const fetchAddExperts = async (params: Record<string, any>) => {
    const { msgFlag, msg, obj } = await addExpertsRun(params);
    msgFlag ? success(msg) : warning(msg);
    if (msgFlag) {
      fetchFindExperts({ id: obj });
    }
  };

  // 编辑专家信息
  const fetchEditExperts = async (params: Record<string, any>) => {
    const { msgFlag, msg, obj } = await editExpertsRun(params);
    msgFlag ? success(msg) : warning(msg);
    if (msgFlag) {
      fetchFindExperts({ id: obj });
    }
  };

  // 查询专家详情
  const fetchFindExperts = async (params: Record<string, any>) => {
    const { msgFlag, msg, obj } = await findExpertsRun(params.id);

    msgFlag ? success(msg) : warning(msg);
    baseInfoForm.setFieldsValue({
      ...obj,
      area: arieaEchoRender(obj),
      birthday: obj?.birthday ? moment(obj.birthday) : undefined,
      industryType: obj?.industryType ? obj?.industryType?.split(',') : undefined,
      overseaType: obj?.overseaType ? obj?.overseaType?.split(',') : undefined,
      talentType: obj?.talentType ? obj?.talentType?.split(',') : undefined,
    });

    dispatch({
      type: IActionEnum.UPDATE_EXPERTS_INFO,
      payload: obj,
    });
    dispatch({
      type: IActionEnum.UPDATE_EXPERTS_QUALIFIES,
      payload: obj?.mexperQualifyList ?? [],
    });
  };

  // 添加证书信息
  const fetchAddExpertsCertificate = async (params: Record<string, any>, onCloseModal: any) => {
    const { msgFlag, msg } = await addExpertsCertificateRun(params);
    if (msgFlag) {
      success(msg);
      fetchFindExperts({ id: expertsInfo.id });
      onCloseModal();
    } else {
      warning(msg);
    }
  };

  // 编辑证书信息
  const fetchEditExpertsCertificate = async (params: Record<string, any>, onCloseModal: any) => {
    const { msgFlag, msg } = await editExpertsCertificateRun(params);
    if (msgFlag) {
      success(msg);
      fetchFindExperts({ id: expertsInfo.id });
      onCloseModal();
    } else {
      warning(msg);
    }
  };

  // 切换证书分页
  const changeCurrent = (operate: string) => {
    if (operate == 'next') {
      setCurrent((prev) => {
        return ++prev;
      });
    } else {
      setCurrent((prev) => {
        return --prev;
      });
    }
  };

  /**
   * 处理表单数据
   */
  const submit = {
    baseInfoSubmit: async () => {
      const result = await baseInfoForm.validateFields();
      // if (!expertQualifies.length) {
      //   warning('请添加证书信息');
      //   return;
      // }
      const params = {
        ...result,
        provinceCode: result?.area ? result?.area[0] : null,
        cityCode: result?.area ? result?.area[1] : null,
        countyCode: result?.area ? result?.area[2] : null,
        mexperQualifyList: expertQualifies,
        industryType: result?.industryType ? result?.industryType?.toString(',') : null,
        overseaType: result?.overseaType ? result?.overseaType?.toString(',') : null,
        talentType: result?.talentType ? result?.talentType?.toString(',') : null,
      };

      delete params?.['area'];
      // expertsInfo.id 表明为专家已存在调用编辑接口
      if (expertsInfo.id) {
        fetchEditExperts({ ...expertsInfo, ...params });
      } else {
        fetchAddExperts(params);
      }
    },
    certificateInfoSubmit: async (onCloseModal: any) => {
      const result = await certificateInfoForm.validateFields();

      // expertsInfo.id 表明为专家已存在单独调用证书接口，不存在即为首次新增专家

      if (expertsInfo.id) {
        const params = {
          expertId: expertsInfo.id,
          ...result,
        };
        if (certificateStatus.operate == 'add') {
          await fetchAddExpertsCertificate(params, onCloseModal);
        } else {
          params['id'] = expertQualifies[current - 1]?.id;
          params['versionNum'] = expertQualifies[current - 1]?.versionNum;

          await fetchEditExpertsCertificate(params, onCloseModal);
        }
      } else {
        dispatch({
          type: IActionEnum.UPDATE_EXPERTS_QUALIFIES,
          payload: [...expertQualifies, result],
        });
        onCloseModal();
        certificateInfoForm.resetFields();
      }
    },
  };

  /**
   * 回显表单数据
   */
  useEffect(() => {
    if (!info) return;
    if (Object.keys(info).length) {
      fetchFindExperts({ id: info.id });
    }
  }, [info]);

  return {
    findExpertsLoading,
    current,
    changeCurrent,
    baseInfoForm,
    certificateInfoForm,
    title,
    isView,
    certificateStatus,
    onChangeExpertsCertificateInfoState,
    ...submit,
  };
}
